package com.czr.service.upload;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description:
 * Author: czr czr
 * Version: 1.0
 * Create Date Time: 2021/12/8 14:03.
 * Update Date Time:
 *
 * @see
 */
@Service
public class TestOssUploadService {

    public String fileUpload(MultipartFile multipartFile) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "oss-cn-shenzhen.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t5Zvm6PjcthF8V42guL";
        String accessKeySecret = "1v59YEIMJzQW8tQSaU58RMidsXGWfm";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "blogczr";

        OSS ossClient = null;
        try {
            // 1：创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 2：获取文件上传的流
            //InputStream inputStream = multipartFile.getInputStream();
            File file;
            InputStream inputStream = multipartFile.getInputStream();
            // 3：构建日期目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());
            // 4：获取文件名
            //String original = multipartFile.getOriginalFilename();
            String original = multipartFile.getOriginalFilename();
            String filename = UUID.randomUUID().toString();
            String suffix = original.substring(original.lastIndexOf("."));
            String newName = filename + suffix;
            String fileUrl = datePath + "/" + newName;

            // 5：上传到阿里云服务器
            ossClient.putObject(bucketName, fileUrl, inputStream);
            return "https://" + bucketName + "." + endpoint + "/" + fileUrl;
        } catch (OSSException e){
            e.printStackTrace();
            return "fail";
        } catch (IOException e) {
            e.printStackTrace();
            return "File not found";
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }

}
